<template>
    <div>
        <div class="talk">
            <p  class="p">
                <span class="iconfont" @click="back()"><a href="###">&#xe634;</a></span>
     
                <router-link :to='"/userdetails/" + list.id'>
                    <img class="img" :src="this.list.photo" alt="">
                    <a href="###">{{this.list.name}}</a>
                </router-link>
            </p>

            <div class="body" ref="Wrapper">
                <ul ref="content">

                    <li v-for="(item,index) in allmess" :key="item.index" :class="{right:item.sId == me.id}">
                        <!-- 用户头像 -->
                        <router-link :to='"/userdetails/" + list.id'>
                            <img class="img" :src="list.photo" alt="" v-if="item.sId != me.id">
                        </router-link>
                        
                        
                        <router-link to="/usercenter">
                            <img class="img" :src="me.photo" alt="" v-if="item.sId == me.id">
                        </router-link>
                        
                        <div :class="{rightdiv:item.sId == me.id}" v-if="item.message.slice(0,4) != 'http'">
                            {{item.message}}
                            
                        </div>

                        <img :class="{rightimg:item.sId == me.id}" v-if="item.message.slice(0,7)=='http://'" :src="item.message" alt="">
                        

                        <p>{{time[index]}}</p>
                    </li>
                </ul>
            </div>

            <div class="input">
                
                <textarea  placeholder="输入内容" v-model="message">
                    <!-- <img :src="photo" alt=""> -->
                </textarea>
                <i class="iconfont">
                    <a href="###" class="emjoy" @click="emoji()">😀</a>
                    <a href="###">&#xe796;</a>
                    <input type="file" class="photo" v-on:input="sendphoto()" ref="photo">
                </i>
                <span @click="send()"><a href="###">发送</a></span>
                <div class="emoji" ref="wrapper">
                    <div>
                        <i v-for="(item,index) in emojilist" :key="item.index" class="allemoji" @click="add(index)"><a href="###">{{item}}</a></i>
                    </div>
                </div>
            </div>

        </div>
    </div>
</template>

<script>
import qs from 'qs'
import axios from 'axios'
import BScroll from 'better-scroll'
import {EventBus} from '../../../../../../static/js/eventBus'
export default {
    name: 'sendmess',

    data () {
        return {
            list: '',
            // img: '',
            me: [],
            sendmess: [],
            allmess: [],
            message: '',
            time: [],
            emojilist: [
                '😀','😁','😂','🤣','😃','😄',
                '😅','😆','😉','😊','😋','😎',
                '😍','😘','😗','😙','😚','🙂',
                '🤗','🤔','😐','😶','🙄','😏',
                '😣','😥','😮','🤐','😯','😪',
                '😫','😴','😌','😛','😜','😝',
                '🤤','😒','😓','😔','😕','🙃',
                '🤑','😲','🙁','😖','😞','😟',
                '😤','😢','😭','😦','😨','😩',
                '😬','😰','😱','😳','😵','😡',
                '😠','😷','🤒','🤕','🤢','🤧',
                '😇','🤠','🤡','🤥','🤓','🌝',
                '🌚','🙈','🙉','🙊','🐵','🐒',
                '💪🏻','👈🏻','👉🏻','☝🏻','👆🏻','🖕🏻',
                '👇🏻','✌🏻','🤞🏻','🖖🏻','🤘🏻','🤙🏻',
                '🖐🏻','✋🏻','👌🏻','👍🏻','👎🏻','✊🏻',
                '👊🏻','🤛🏻','🤜🏻','🤚🏻','👋🏻','✍🏻',
                '👏🏻','👐🏻','🙏🏻','💅🏻','💘',
                '💓','💔','💕','💝','🚶','🏃',
                '💃🏼','👯‍♂️','👩‍❤️‍👩','🍋','🍎','🍑',
                '🍒','🍓','🍉','🍇','🥑','🍌',
                '🍗','🍔','🍟','🌭','🍱','🍚',
                '🍜','🍦','🍨','🥛','☕','🍻',
                '🌛','🎃','🎄','✨','🎋','🎍',
                '😈','👿','👹','👺','💀','👻',
                '👽','🤖','💩','👬','👭','👄',
                '👂🏻','👃🏻','👣','👀','👁','👅',
                '👓','🕶','👔','👕','👖','👗',
                '👘','👙','👚','👛','👜','👝',
                '💼','🎒','👞','👟','👠','👡',
                '👢','👑','👒','🎩','🎓','⛑',
                '💄','💍','🌂',
            ],
            isemoji: true,
            newphoto: '',
        }
    },

    created () {

        axios.post(`/api/user/getUser`, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

            if (response.status === 200) {
                this.me = response.data
                // console.log(this.me)
            } 

        })

        let id = this.$route.params.id

        axios.post(`/api/chat/${id}`, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

            if (response.status === 200) {
                this.allmess = response.data
                console.log(this.allmess)
                
                var date = new Date()
                var now = date.getTime()

                var year = date.getFullYear()
                // 月份从0开始，0表示一月，所以得加一
                var mon = date.getMonth() + 1
                // getDay()是获取星期几，从0开始
                var day = date.getDate()
                var hour = date.getHours()
                var min = date.getMinutes()

                // console.log(now)

                // console.log(year)
                // console.log(mon)
                // console.log(day)
                // console.log(hour)
                // console.log(min)
                // console.log(this.allmess[115].message.slice(0,4))

                for (var i = 0; i < this.allmess.length; i++) {

                    if (year == this.allmess[i].time.slice(0,4) && mon == this.allmess[i].time.slice(5,7) && day == this.allmess[i].time.slice(8,10) ) {

                        if (hour >= this.allmess[i].time.slice(11,13) && min >= this.allmess[i].time.slice(14,16)) {
                            this.time.push(this.allmess[i].time.slice(11,16))
                        }
                    }
                    else if (year == this.allmess[i].time.slice(0,4) && mon == this.allmess[i].time.slice(5,7) && day-1 == this.allmess[i].time.slice(8,10)) {
                        this.time.push("昨天 "+this.allmess[i].time.slice(11,16))

                    }
                    else if (year == this.allmess[i].time.slice(0,4) && mon >= this.allmess[i].time.slice(5,7)) {

                        this.time.push(this.allmess[i].time.slice(5,10)+' '+this.allmess[i].time.slice(11,16))

                    }
                    else if (year > this.allmess[i].time.slice(0,4)) {

                        this.time.push(this.allmess[i].time.slice(0,10)+' '+this.allmess[i].time.slice(11,16))
                    }
                    
                    // console.log(this.allmess[i].time.slice(0,4))
                    // console.log(this.allmess[i].time.slice(5,7))
                    // console.log(this.allmess[i].time.slice(8,10))
                    // console.log(this.allmess[i].time.slice(11,13))
                    // console.log(this.allmess[i].time.slice(14,16))
                    // console.log(this.allmess[i].time.slice(11,16))
                }
                console.log(this.time)

            } 

        })

        // userdetails发送数据
        EventBus.$on('send',(list) => {
            this.list = list;
            console.log(this.list)
        })
        
        // blogdetails发送数据
        EventBus.$on('sendblog',(list) => {
            this.list = list;
            console.log(this.list)
        })

        // letter发送数据
        EventBus.$on('sendletter',(list) => {
            this.list = list;
            console.log(this.list)
        })
        
    },

    mounted () {
        this.scroll = new BScroll(this.$refs.Wrapper)
        this.$nextTick(() => {
        // 解决移动端因vue数据更新异步而无法滚动的问题
            this.scroll = new BScroll(this.$refs.Wrapper, {
                click:true, //设置click参数，使单句歌词可点击
                adjustTime: 350, // 拉动之后的返回时间，默认400
                mouseWheel: true,
            })

            // setInterval(() => {
            this._initScroll();
            let Lis = this.$refs.Wrapper.querySelectorAll("li"); // 查找所有li元素
            this.scroll.scrollToElement( Lis[Lis.length - 1], 300 );  // 滑动到指定元素,设置动画300ms
            // },1000)
        }) 

        // 实现enter发送，shift+enter换行
        var _this = this
        document.onkeydown = function () {
            if (!event.shiftKey && event.keyCode === 13) {
                _this.send()
            }
        }

        setInterval(() => {
            let id = this.$route.params.id

            axios.post(`/api/chat/${id}`, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

                if (response.status === 200) {
                    this.allmess = response.data
                    console.log(this.allmess)
                } 

            })
            
        },10000)
    },

    updated() {

        this.$nextTick(() => {
            this._initScroll();
            let Lis = this.$refs.Wrapper.querySelectorAll("li"); // 查找所有li元素
            this.scroll.scrollToElement( Lis[Lis.length - 1], 300 );  // 滑动到指定元素,设置动画300ms
        });

    },

    methods: {
        _initScroll() {
            // 此种写法防止内存泄漏
            if (!this.scroll) {
                // 如果不存在，创建新的BScroll实例
                this.scroll = new BScroll(this.$refs.Wrapper, {
                    click: true
                });
            } else {
                // 如果存在，直接刷新
                this.scroll.refresh();
            }
        },

        send () {
            if (this.me != "") {
                if (this.message != "") {
                    let postData = qs.stringify({
                        rId: this.$route.params.id,
                        message: this.message,
                    })

                    axios.post(`/api/sentMessage`, postData, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

                        if (response.status === 200) {
                            console.log(response.data)

                            let id = this.$route.params.id

                            axios.post(`/api/chat/${id}`, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

                                if (response.status === 200) {
                                    this.allmess = response.data
                                    // console.log(this.allmess)
                                } 
                            })

                        } 

                    })

                    let id = this.$route.params.id

                    axios.post(`/api/chat/${id}`, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

                        if (response.status === 200) {
                            this.allmess = response.data
                            console.log(this.allmess)
                        } 

                    })
                }
                else {
                    this.$message({
                        type: 'error',
                        message: "消息不允许为空！"
                    })
                    
                }
                
            }
            else {
                this.$message({
                    type: 'warn',
                    message: "请先登录！"
                })
            }
            this.message = ""

        },

        back () {
            this.$router.go(-1)
        },

        emoji () {
            this.scroll = new BScroll(this.$refs.wrapper)
            this.$nextTick(() => {
            // 解决移动端因vue数据更新异步而无法滚动的问题
                this.scroll = new BScroll(this.$refs.wrapper, {
                    click:true, //设置click参数，使单句歌词可点击
                    // adjustTime: 350, // 拉动之后的返回时间，默认400
                    mouseWheel: true,
                    
                })

            })

            if (this.isemoji) {
                document.getElementsByClassName("input")[0].style.position = "absolute"
                document.getElementsByClassName("input")[0].style.bottom = "0rem"
                this.isemoji = !this.isemoji
            }
            else {
                document.getElementsByClassName("input")[0].style.position = "relative"
                this.isemoji = !this.isemoji
            }
            
        },

        add (index) {
            this.message = this.message+this.emojilist[index]
            console.log(this.emojilist[index])
        },

        getBase64 (file) {
            return new Promise(function (resolve, reject) {
            let reader = new FileReader()
            let imgResult = ''
            reader.readAsDataURL(file)
            reader.onload = function () {
                imgResult = reader.result
            }
            reader.onerror = function (error) {
                reject(error)
            }
            reader.onloadend = function () {
                resolve(imgResult)
            }
            })
        },

        dataURItoBlob (dataURI) {
            // base64 解码
            // console.log('dataURI', dataURI)
            let byteString = window.atob(dataURI.split(',')[1])
            let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
            // let T = mimeString.split('/')[1]
            let ab = new ArrayBuffer(byteString.length)
            let ia = new Uint8Array(ab)
            for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i)
            }
            return new Blob([ab], {type: mimeString})
        },

        sendphoto () {
            let data = this.$refs.photo.files[0]
            console.log('data', data)
            // this.photoname = data.name
            // console.log(this.photoname)
            // console.log(this.getBase64(data))
            this.getBase64(data).then(res => {
                // this.newphoto = res
                console.log(res)
                // document.getElementsByTagName("textarea").innerHTML = '<img :src="res" alt="">'
                // this.photo = res
                // console.log('this.newphoto', this.newphoto)
                this.newphoto = this.dataURItoBlob(res)
                // console.log('newphoto', this.newphoto)
                if (this.newphoto !== '') {

                    var formdata = new FormData()
                    formdata.append('photo', this.newphoto)
                    console.log(formdata,"true")

                    axios.post(`/api/blogPhoto`, formdata, {headers:{'Content-type': 'multipart/form-data'}}).then((response) => {

                        if (response.status === 200) {
                            this.$message({
                            type: 'success',
                            message: "已发送"
                            })

                            let postData = qs.stringify({
                                rId: this.$route.params.id,
                            })

                            axios.post(`/api/chatImage`, postData, {headers:{'Content-type': 'application/x-www-form-urlencoded'}}).then((response) => {

                                if (response.status === 200) {
                                    console.log(response.data)
                                } 
                            })
                            
                        } 

                    })

                }
            })
        }


    },

}
</script>

<style lang="stylus" scoped>
.talk
    width 78%
    height 40rem
    overflow hidden
    left 13%
    top 5rem
    position absolute
    margin-bottom 2rem
    border 1px #ccc solid
    border-radius 10px
    box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
    background-color #fff
    .p
      width 100%
      text-align center
      line-height 3.5rem
      font-size 1rem
      position relative
      border-bottom .05rem #ccc solid
      // background-color red
      span
        width 5%
        line-height 3.5rem
        position absolute
        left 0rem
        font-size 2rem
        // background-color #fff
    .img
      width 2.5rem
      height 2.5rem
      border-radius 50%
      margin-left -10%
      box-shadow 0 0 0.266667rem rgba(131, 171, 175, 0.5)
    .body
      width 100%
      height 80%
      overflow hidden
      padding-bottom 1rem
      background-color #eee
      ul
        width 100%
        height auto
        padding-bottom 1rem
        // background-color skyblue
        li
          display flex
          width 55%
          min-height 2rem
          margin-top 1rem
          padding .5rem
          position relative
          //background-color red
          .img
            height 2.5rem 
            width 2.5rem
            position absolute 
            border-radius 50%   
            margin-left 0rem
            margin-top -.4rem
            box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
          div
            max-width 88%
            margin-left 9%
            line-height 1rem
            padding .5rem
            font-size .8rem
            border .05rem #eee solid
            border-radius 10px
            border-top-left-radius 0px
            box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
            background-color #fff
          img
            width 40%
            height auto
            margin-left 10%
            border .05rem #eee solid
            border-radius 10px
            box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
            background-color #ccc
          p
            position absolute
            margin-left 71%
            bottom -1rem
            color #aaa
        .right
          flex-direction row-reverse
          display flex
          width 50%
          margin-top 1rem
          margin-left 48%
          padding .5rem
          position relative
          //background-color red
          .img
            display block
            height 2.5rem 
            width 2.5rem
            border-radius 50%   
            position absolute
            right 0rem
            top .5rem
            box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
          .rightdiv
            margin-right 2.5rem
            line-height 1rem
            padding .5rem
            font-size .8rem
            border .05rem #eee solid
            border-radius 10px
            border-top-right-radius 0px
            box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
            background-color #fff
          .rightimg
            margin-right 2.5rem
            border .05rem #eee solid
            border-radius 10px
            box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
            background-color #ccc
          p
            position absolute 
            left -84%
.input
    width 100%
    line-height 5rem
    margin-bottom 0rem
    position relative
    border-top .05rem #ccc solid
    background-color #fff
    textarea 
      width 70%
      height 3rem
      margin-left 6%
      text-indent 1rem
      font-size .9rem
      border-radius 5px
      margin-top -1.5rem
      border .05rem #333 solid
    i 
      display inline-block
      width 10%
      height 1.5rem
      margin-top -2.5rem
      //background-color red
      a
        font-size 1.8rem
        margin-left 72%
      .emjoy
        font-size 1.2rem
        position absolute
        margin-left 2%
      a:hover 
        color skyblue
    span 
      position absolute 
      top .7rem
      right 6%
      line-height 2rem
      padding .1rem .5rem
      font-size .8rem
      border .05rem #eee solid
      border-radius 10px
      box-shadow: 0 0 0.266667rem rgba(131, 171, 175, 0.5);
      background-color #fff
    span:hover
      background-color skyblue
      a
        color #fff
    .emoji
      box-sizing border-box
      height 17rem
      line-height 1rem
      overflow hidden
      width 100%
      padding 0 3rem
      position relative
      margin-top -1rem
      border-top .05rem #ccc solid
      background-color #fff
      .allemoji
        width 3%
        display inline-block
        margin-left 1%
        text-align center
        margin-top .5rem
        // background-color red
        a
          font-size 1.3rem
          margin-left -.1rem
    .photo
        position absolute 
        top 1.2rem
        right 12%
        width 6%
        opacity 0
        // background-color red
</style>